<template>
  <div class="home-container">
    <Header />

    <div class="content clearfix">
      <div class="list">
        <Button type="primary" ghost style="margin-right: 10px" @click="showCreateDialog">新建绘本</Button>
      </div>

      <Table
        style="min-height: 60vmin;"
        :loading="loading"
        :columns="columns"
        :data="tableData"
      >
        <template slot-scope="{ row, index }" slot="action">
          <Button type="error" ghost @click="remove(row, index)">删除</Button>
        </template>
      </Table>

      <Page
        class-name="pagination"
        show-total
        show-sizer
        :total="total"
        @on-page-size-change="handlePageSizeChange"
        @on-change="handleCurrentChange"
        :page-size="pageSize"
        :page-size-opts="pageSizeOpts"
        :current="pageNo"
        v-if="!loading && total > 0"
      />
    </div>

    <Footer />

    <!-- 新建绘本对话框 -->
    <Drawer
      :title="drawerTitle"
      v-model="isShowDrawer"
      width="600"
      :styles="styles"
      :mask-closable="true"
    >
      <Form :model="form" ref="form" :rules="rules">
        <FormItem label="绘本名称" prop="content" label-position="left" :label-width="85">
          <Input v-model="form.content" placeholder="请输入绘本名称" />
        </FormItem>

        <FormItem label="绘本图片" prop="image" label-position="left" :label-width="85">
          <div class="image-upload">
            <input
              type="file"
              accept="image/*"
              @change="handleImageUpload"
              ref="imageInput"
              style="display: none"
            />
            <Button @click="$refs.imageInput.click()">选择图片</Button>
            <div v-if="form.previewImage" class="preview-image">
              <img :src="form.previewImage" alt="预览" style="max-width: 200px; max-height: 150px" />
            </div>
          </div>
        </FormItem>
      </Form>

      <div class="demo-drawer-footer">
        <Button type="primary" @click="handleSubmit" v-if="isCreate">提交</Button>
     
        <Button type="error" ghost @click="isShowDrawer = false" v-if="isCreate">取消</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import store from '../store';
import { formatTime, formatDate } from '@/utils/valid';
import { createDrawtail, deleteDrawtail, getAllDrawtailByName } from '@/utils/api';
import { uploadUrl,url } from '@/utils/url';
import axios from 'axios';

export default {
  name: 'Home',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      content: '',
      apiUrl: uploadUrl,
      loading: false,
      tableData: [],
      columns: [
        {
          title: '绘本名字',
          key: 'content',
          width: 300,
          align: 'center',
          sortable: true
        },
        {
          title: '图片',
          key: 'image',
          width: 250,
          render: (h, params) => {
            const row = params.row;
            return h('img', {
              style: {
                height: '32px',
                width: '32px',
                objectFit: 'cover'
              },
              domProps: {
                src: this.getImageUrl(row.image)
              }
            });
          }
        },
        {
          title: '内容',
          key: 'content'
        },
        {
          title: '操作',
          width: 200,
          slot: 'action',
          align: 'center'
        }
      ],
      total: 0,
      pageSize: 10,
      pageSizeOpts: [10, 20, 30, 40],
      pageNo: 1,
      isShowDrawer: false,
      drawerTitle: '新建绘本',
      isCreate: true,
      form: {
        name: '',
        image: null,
        previewImage: ''
      },
      rules: {
        name: [{ required: true, message: '绘本名称不能为空', trigger: 'blur' }],
        image: [{ required: true, message: '请上传绘本图片' }]
      },
      styles: {}
    };
  },
  created() {
    this.data = localStorage.getItem('name');
    this.getTaskList();
  },
  mounted() {
    this.normalUserID = 0;
    let user_type = store.state.userInfo.data.userData.user_type;
    if (user_type != 1) {
      this.normalUserID = store.state.userInfo.data.userData.id;
    }
  },
  methods: {
    getImageUrl(imagePath) {
      if (!imagePath) return '';
      return imagePath.startsWith('http') ? imagePath : `${this.apiUrl}${imagePath}`;
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getTaskList();
    },
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.getTaskList();
    },
    getTaskList() {
      this.loading = true;
      getAllDrawtailByName({ name: this.data })
        .then(res => {
          this.loading = false;
          if (res.code === 0 && res.data) {
            this.tableData = res.data.map(item => ({
              name: item.name,
              content: item.content,
              image: item.image
            }));
            this.total = res.data.length;
          } else {
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    showCreateDialog() {
      this.isShowDrawer = true;
      this.isCreate = true;
      this.drawerTitle = '新建绘本';
      this.$refs.form && this.$refs.form.resetFields();
    },
    handleImageUpload(e) {
      const file = e.target.files[0];
      if (!file) return;
      
      // 验证文件类型
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$Message.error('只能上传图片文件');
        return;
      }
      
      // 验证文件大小
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$Message.error('图片大小必须小于 2MB');
        return;
      }
      
      // 保存文件对象
      this.form.image = file;
      
      // 读取文件并预览
      const reader = new FileReader();
      reader.onload = (e) => {
        this.form.previewImage = e.target.result;
      };
      reader.readAsDataURL(file);
      
      // 触发表单验证
      this.$refs.form.validateField('image');
    },
 // 正确的方法实现
handleSubmit() {
  this.$refs.form.validate(valid => {
    console.log('表单验证结果:', valid);
    if (!valid) return;

    const formData = new FormData();
    formData.append('content', this.form.content);  // 注意字段对应关系
    formData.append('name', this.data);
    if (this.form.image) {
      formData.append('file', this.form.image);
    }

    // 使用正确配置的URL
    axios.post(url+`api/createDrawtail`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
     
      }
    })
    .then(response => {
      console.log('响应数据:', response);  // 添加响应日志
      if (response.data.code === 0) {
        this.$Message.success('创建成功');
        this.getTaskList();
        this.isShowDrawer = false;
      }
    })
    .catch(error => {
      console.error('请求失败:', error);  // 添加错误日志
      this.$Message.error('请求发送失败');
    });
  });
},
    handleReset() {
      this.$refs.form.resetFields();
      this.form.image = null;
      this.form.previewImage = null;
    },
    remove(row, index) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '确定要删除该绘本吗？',
        onOk: () => {
          deleteDrawtail({ name: row.name, content: row.content ,image:row.image})
            .then(res => {
              if (res.code === 0) {
                this.$Message.success('删除成功');
                this.tableData.splice(index, 1);
                this.total--;
              } else {
                this.$Message.error(res.msg || '删除失败');
              }
            })
            .catch(err => {
              console.error(err);
              this.$Message.error('删除失败');
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.home-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .content {
    .list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
  }
}

.image-upload {
  display: flex;
  flex-direction: column;
}

.preview-image {
  margin-top: 10px;
  text-align: center;
}
</style>

<style lang="scss">
.ivu-table-tip table td {
  width: 100% !important;
}

.pagination {
  float: right;
  margin: 20px 0;
}

.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 16px;
  background: #fff;
  display: flex;
  justify-content: flex-end;
}
</style>